package com.gui;

import com.util.MultimediaLauncher;
import com.util.MediaPanel;
import com.vo.Event;
import com.vo.Interval;
import com.vo.Note;
import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;
import java.util.*;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/**
 *
 * @author Carla Sukeyosi
 */
public class NotesForm extends JFrame {
    
    private Event event;
    private Elephant main;
    private Note noteKey;
    private List<URL> videosList;
    private List<URL> imageList;
    private List<URL> audioList;
    
    public NotesForm(Event event, Elephant main)
    {
        this.main = main;
        if (event != null)
            this.event = event;
        else
            event = new Event("", "", new Interval());
        initComponents();
        loadEvent();
    }
    
    public NotesForm() 
    {
        event = new Event("", "", new Interval());
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        main_panel = new javax.swing.JPanel();
        event_notes = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        title_jTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        body_jTextArea = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        notes_jList = new javax.swing.JList();
        loadMultimedia_jButton = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        audio_list = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        imagesList = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel();
        newNote_jButton = new javax.swing.JButton();
        addNote_jButton = new javax.swing.JButton();
        jScrollPane5 = new javax.swing.JScrollPane();
        videoList = new javax.swing.JList();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Anotações");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        event_notes.setFont(new java.awt.Font("Tahoma", 0, 24));
        event_notes.setText("Anotações");

        jLabel2.setText("Título:");

        jLabel3.setText("Corpo:");

        body_jTextArea.setColumns(20);
        body_jTextArea.setRows(5);
        jScrollPane1.setViewportView(body_jTextArea);

        notes_jList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                notes_jListMouseExited(evt);
            }
        });
        notes_jList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                notes_jListValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(notes_jList);

        loadMultimedia_jButton.setText("Carregar Multimídia");
        loadMultimedia_jButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadMultimedia_jButtonActionPerformed(evt);
            }
        });

        audio_list.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                audio_listMouseExited(evt);
            }
        });
        audio_list.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                audio_listValueChanged(evt);
            }
        });
        jScrollPane3.setViewportView(audio_list);

        jLabel1.setText("Áudio:");

        imagesList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                imagesListMouseExited(evt);
            }
        });
        imagesList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                imagesListValueChanged(evt);
            }
        });
        jScrollPane4.setViewportView(imagesList);

        jLabel4.setText("Imagens:");

        newNote_jButton.setText("Novo");
        newNote_jButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newNote_jButtonActionPerformed(evt);
            }
        });

        addNote_jButton.setText("Adicionar");
        addNote_jButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addNote_jButtonActionPerformed(evt);
            }
        });

        videoList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                videoListMouseExited(evt);
            }
        });
        videoList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                videoListValueChanged(evt);
            }
        });
        jScrollPane5.setViewportView(videoList);

        jLabel5.setText("Videos:");

        javax.swing.GroupLayout main_panelLayout = new javax.swing.GroupLayout(main_panel);
        main_panel.setLayout(main_panelLayout);
        main_panelLayout.setHorizontalGroup(
            main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(main_panelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(event_notes)
                    .addGroup(main_panelLayout.createSequentialGroup()
                        .addGroup(main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(main_panelLayout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(12, 12, 12))
                            .addGroup(main_panelLayout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(227, 227, 227))
                            .addGroup(main_panelLayout.createSequentialGroup()
                                .addComponent(jScrollPane5, 0, 0, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(main_panelLayout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(32, 32, 32)
                                .addComponent(title_jTextField))
                            .addGroup(main_panelLayout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(29, 29, 29)
                                .addGroup(main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE)
                                    .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(loadMultimedia_jButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                        .addGap(18, 18, 18)
                        .addGroup(main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(newNote_jButton, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
                            .addComponent(addNote_jButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addGap(56, 56, 56))
        );
        main_panelLayout.setVerticalGroup(
            main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(main_panelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(event_notes)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(main_panelLayout.createSequentialGroup()
                        .addGroup(main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(title_jTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(newNote_jButton))
                        .addGap(18, 18, 18)
                        .addGroup(main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(main_panelLayout.createSequentialGroup()
                                .addGroup(main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1)
                                .addGap(4, 4, 4)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(loadMultimedia_jButton))
                            .addComponent(addNote_jButton)))
                    .addGroup(main_panelLayout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(main_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(main_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        if (event != null)
            this.main.setEventKey(event);
        main.setVisible(true);
    }//GEN-LAST:event_formWindowClosed

    private void notes_jListMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_notes_jListMouseExited
        notes_jList.clearSelection();
    }//GEN-LAST:event_notes_jListMouseExited

    private void notes_jListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_notes_jListValueChanged
        int index = notes_jList.getSelectedIndex();
        if (!(index < 0))
        {
            noteKey = (Note) event.getNotes().get(index);
            title_jTextField.setText(noteKey.getTitle());
            body_jTextArea.setText(noteKey.getBody());
            
            reloadMultimediaLists();
        }
    }//GEN-LAST:event_notes_jListValueChanged

    private void loadMultimedia_jButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadMultimedia_jButtonActionPerformed
         JFileChooser fileChooser = new JFileChooser();
         int result = fileChooser.showOpenDialog( null );

         if ( result == JFileChooser.APPROVE_OPTION )
         {
            URL mediaURL = null;
            String path = null;
            
            try
            {
                mediaURL = fileChooser.getSelectedFile().toURI().toURL();
                path = fileChooser.getSelectedFile().toURI().toURL().toString();
            }
            catch ( MalformedURLException malformedURLException )
            {
                System.err.println( "Erro ao tentar criar URL." );
            }
            
            if ( mediaURL != null )
            {
                String destiny = "src" + File.separator + "com" + File.separator
            + "files" + File.separator;
                
                String fileName = null;

                 if (path.contains(File.separator))
                     fileName = path.substring(path.lastIndexOf(File.separator));
                 else if (path.contains(File.pathSeparator))
                     fileName = path.substring(path.lastIndexOf(File.pathSeparator));
                 else if (path.contains("/"))
                     fileName = path.substring(path.lastIndexOf("/"));
                 else
                 {
                     System.out.println("Erro ao tentar copiar arquivo");
                     return;
                 }
                 if (path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".jpeg")
                    || path.endsWith(".bmp") || path.endsWith(".gif"))
                 {
                     destiny += "images" + File.separator;
                     try 
                     {
                         File file = new File(destiny + fileName);
                         noteKey.addImage(file.toURI().toURL());
                     } catch (Exception ex)
                     {
                         System.out.println(ex.getMessage());
                     }
                 } 
                 else if (path.endsWith(".mp3"))
                 {
                     destiny += "audios" + File.separator;
                     try 
                     {
                         File file = new File(destiny + fileName);
                         noteKey.addAudio(file.toURI().toURL());
                     } catch (Exception ex)
                     {
                         System.out.println(ex.getMessage());
                     }
                 }
                 else if (path.endsWith(".avi") || path.endsWith(".swf") || path.endsWith(".mpg")
                         || path.endsWith(".mov"))
                 {
                     destiny += "videos" + File.separator;
                     try 
                     {
                         File file = new File(destiny + fileName);
                         noteKey.addVideo(file.toURI().toURL());
                     } catch (Exception ex)
                     {
                         System.out.println(ex.getMessage());
                     }
                 } else
                 {
                     System.out.println("Arquivo inválido.");
                     return;
                 }
                 try 
                 {
                     FileInputStream fis = new FileInputStream(new File(mediaURL.toURI()));
                     FileOutputStream fos = new FileOutputStream(new File(destiny + fileName));
                     FileChannel destinyFC;
                     
                    FileChannel sourceFC = fis.getChannel();
                    destinyFC = fos.getChannel();
                    sourceFC.transferTo(0, sourceFC.size(), destinyFC);
                    
                     destinyFC.close();
                 } catch (Exception ex)
                 {
                        System.out.println(ex.getMessage());
                 }
                 reloadMultimediaLists();
            }
          }
    }//GEN-LAST:event_loadMultimedia_jButtonActionPerformed

    private void audio_listMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_audio_listMouseExited
        audio_list.clearSelection();
    }//GEN-LAST:event_audio_listMouseExited

    private void audio_listValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_audio_listValueChanged
        int index = audio_list.getSelectedIndex();
        if (!(index < 0))
        {
            URL mediaURL = audioList.get(index);
            loadMultimediaLauncher(index, mediaURL);
        }
    }//GEN-LAST:event_audio_listValueChanged

    private void imagesListMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imagesListMouseExited
        imagesList.clearSelection();
    }//GEN-LAST:event_imagesListMouseExited

    private void imagesListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_imagesListValueChanged
        int index = imagesList.getSelectedIndex();
        if (!(index < 0))
        {
            URL mediaURL = imageList.get(index);
            loadMultimediaLauncher(index, mediaURL);
        }
    }//GEN-LAST:event_imagesListValueChanged

    private void videoListMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_videoListMouseExited
        imagesList.clearSelection();
    }//GEN-LAST:event_videoListMouseExited

    private void videoListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_videoListValueChanged
        int index = videoList.getSelectedIndex();
        if (!(index < 0))
        {
            URL mediaURL = videosList.get(index);
            loadMultimediaLauncher(index, mediaURL);
        }
        
    }//GEN-LAST:event_videoListValueChanged

    private void addNote_jButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addNote_jButtonActionPerformed
        newNote_jButton.setEnabled(true);
        addNote_jButton.setEnabled(false);
        activateNoteForm(false);
        reloadMultimediaLists();
        loadEvent();
        addNote();
    }//GEN-LAST:event_addNote_jButtonActionPerformed

    private void newNote_jButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newNote_jButtonActionPerformed
        newNote_jButton.setEnabled(false);
        addNote_jButton.setEnabled(true);
        noteKey = new Note();
        activateNoteForm(true);
    }//GEN-LAST:event_newNote_jButtonActionPerformed

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(NotesForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() 
        {
            public void run() 
            {
                new NotesForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addNote_jButton;
    private javax.swing.JList audio_list;
    private javax.swing.JTextArea body_jTextArea;
    private javax.swing.JLabel event_notes;
    private javax.swing.JList imagesList;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JButton loadMultimedia_jButton;
    private javax.swing.JPanel main_panel;
    private javax.swing.JButton newNote_jButton;
    private javax.swing.JList notes_jList;
    private javax.swing.JTextField title_jTextField;
    private javax.swing.JList videoList;
    // End of variables declaration//GEN-END:variables

    private void loadEvent() 
    {
        if (event != null)
        {
            title_jTextField.setEditable(false);
            body_jTextArea.setEditable(false);
            event_notes.setText("Anotações de " + event.getName() + ".");
            List<Note> list = event.getNotes();
            List<String> names = new ArrayList<String>();
            
            for (Note n : list)
            {
                names.add(n.getTitle());
            }

            notes_jList.setListData(names.toArray());
        }
    }
    
    private void reloadMultimediaLists ()
    {
        imageList = noteKey.getImagesList();
        videosList = noteKey.getVideosList();
        audioList = noteKey.getAudioList();
        
        ArrayList<String> names = new ArrayList<String>();
            
            for (URL url : imageList)
            {
                try 
                {
                    names.add(url.toURI().toURL().toString());
                } catch (Exception ex)
                {
                    System.out.println(ex.getMessage());
                }
            }
            
            imagesList.setListData(names.toArray());
            names.removeAll(names);
            
            for (URL url : videosList)
            {
                try 
                {
                    names.add(url.toURI().toURL().toString());
                } catch (Exception ex)
                {
                    System.out.println(ex.getMessage());
                }
            }
            
            videoList.setListData(names.toArray());
            names.removeAll(names);
            for (URL url : audioList)
            {
                try 
                {
                    names.add(url.toURI().toURL().toString());
                } catch (Exception ex)
                {
                    System.out.println(ex.getMessage());
                }
            }
            
            audio_list.setListData(names.toArray());
            names.removeAll(names);
    }

    private void loadMultimediaLauncher(int index, URL mediaURL) 
    {
        this.setVisible(false);
        final MultimediaLauncher multimediaLauncher = new MultimediaLauncher( "Media Tester" );
        multimediaLauncher.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );

        MediaPanel mediaPanel = new MediaPanel( mediaURL );
        multimediaLauncher.add( mediaPanel );

        multimediaLauncher.setSize( 300, 300 );
        multimediaLauncher.setVisible( true );

        multimediaLauncher.nForm = this;
        
        multimediaLauncher.player  = mediaPanel.getPlayer();
        multimediaLauncher.addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosed(java.awt.event.WindowEvent evt) {
            multimediaLauncher.formWindowClosed(evt);
            
        }
        });
    }

    private void activateNoteForm(boolean b) 
    {
        title_jTextField.setEditable(b);
        body_jTextArea.setEditable(b);
        title_jTextField.requestFocus(b);
        loadMultimedia_jButton.setEnabled(b);
    }

    private void addNote() 
    {
        noteKey.setBody(body_jTextArea.getText());
        noteKey.setTitle(title_jTextField.getText());
        event.addNote(noteKey);
    }
}
